const bcrypt = require('bcrypt');
const { pool } = require('../config/db');

class User {
  // 创建新用户
  static async create(userData) {
    const { username, email, password } = userData;
    // 密码加密
    const hashedPassword = await bcrypt.hash(password, 10);
    const query = 'INSERT INTO users (username, email, password) VALUES (?, ?, ?)';
    const [result] = await pool.execute(query, [username, email, hashedPassword]);
    return result.insertId;
  }

  // 根据邮箱查找用户
  static async findByEmail(email) {
    const query = 'SELECT * FROM users WHERE email = ?';
    const [rows] = await pool.execute(query, [email]);
    return rows[0];
  }

  // 根据ID查找用户
  static async findById(id) {
    const query = 'SELECT * FROM users WHERE id = ?';
    const [rows] = await pool.execute(query, [id]);
    return rows[0];
  }

  // 验证密码
  static async comparePassword(inputPassword, hashedPassword) {
    return bcrypt.compare(inputPassword, hashedPassword);
  }

  // 更新用户信息
  static async update(id, userData) {
    const { username, email } = userData;
    const query = 'UPDATE users SET username = ?, email = ? WHERE id = ?';
    await pool.execute(query, [username, email, id]);
  }

  // 修改密码
  static async changePassword(id, newPassword) {
    const hashedPassword = await bcrypt.hash(newPassword, 10);
    const query = 'UPDATE users SET password = ? WHERE id = ?';
    await pool.execute(query, [hashedPassword, id]);
  }
}

module.exports = User;